<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/6/26
 * Time: 17:03
 */
namespace Institution\Controller;
use Think\Controller;
use User\Api\UserApi;
class AttachmentController extends AdminController{
    public function index(){
        //判断用户是否为机构管理员
        //如果是的话就读取所有机构的附件
//        if(is_jigouadmin()){
//            $where['AgencyId'] = DEPARTMENT_ID;
//        }
//        $uid=M('auth_group_access')->where(array('uid'=>UID))->getField('group_id');
//        $maps['title'] = array("like","%机构管理员%");
//        $gid=M('auth_group')->where($maps)->getField('id');
//        if ($uid==$gid) {//判断当前登陆用户是否为管理员
//
//        }else{
//
//        }
        $info = M('User')->find(UID);
        //搜索标题
        $xmmc = I('xmmc');
        if($xmmc){
            $where['xmmc']= array('LIKE',"%$xmmc%");
            $this->assign('xmmc',$xmmc);
        }
        $model = M('Task');
        $where['department_id'] = $info['department'];
        $list = $this->lists(M('kjcx'),$where);
        $this->assign('meta_title', '附件');
//        $list = M('Task')->where($where)->join('k_kjcx ON k_task.kjcxid=k_kjcx.id')->select();
        $this->assign('list',$list);
        $this->display();
    }

    public function upload(){
        if(IS_POST){
            $type = I('post.typeid');
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     3145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg', 'doc');// 设置附件上传类型
            switch($type){
                case "1":
                    $upload->rootPath  =      './Uploads/shenqingbiao'; // 设置附件上传根目录
                    break;
                case "2":
                    $upload->rootPath  =      './Uploads/fapiao'; // 设置附件上传根目录
                    breal;
                case "3":
                    $upload->rootPath  =      './Uploads/report'; // 设置附件上传根目录
            }

            $upload->saveName = '';
            // 上传单个文件
            $info   =   $upload->uploadone($_FILES['photo']);
            if(!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            }else{// 上传成功 获取上传文件信息
                $file = array(
                    'uid'=>UID,
                    'title'=>$info['savename'],
                    'dir'=>$upload->rootPath,
                    'create_time'=>NOW_TIME,
                    'size'=>$info['size'],
                    'type'=>$type
                );
                M('Attachment')->add($file);
                $this->success('上传成功',U('Attachment/index'));
            }
        }

    }

    function get_user_qx($user_bh = '',$qx_ids='0')
    {
        $process_list	=	$this->get_process();//获取业务流程
        $tmp_v 		= explode(',',$qx_ids);
        $where_arr 	= array();
        //获取用户当前的任务流程信息
        foreach($tmp_v as $v)
        {
            if(!empty($process_list[$v]))
            {
                $tmp_value = $process_list[$v];
                //全显账号
                if(!empty($tmp_value['show_user_id']))
                {
                    $tmp_kkk = explode(',',$tmp_value['show_user_id']);
                    if(in_array($user_bh, $tmp_kkk))
                    {
                        $where_arr[] = sprintf('( `k_kjcx`.`process_id` = %d)',$v);
                    }
                }
                if(!empty($tmp_value['check_user']))
                {

                    //无需要测试当前用户，适用于值班人员
                    if($tmp_value['check_user_tag'] == 0 || empty($tmp_value['show_button_tag']) )
                    {
                        $tmp_kkk = explode(',',$tmp_value['check_user']);

                        if(in_array($user_bh, $tmp_kkk))
                        {
                            $where_arr[] = sprintf('( `k_kjcx`.`process_id` = %d)',$v);
                        }
                    }
                    else
                    {
                        //当前流程需要检测当前用户
                        $tmp_v = json_decode(htmlspecialchars_decode($tmp_value['show_button_tag']),true);
                        foreach($tmp_v as $key => $item)
                        {
                            switch($item['type'])
                            {
                                case 'session_user':
                                    $tmp_arr 		= array();
                                    $tmp_arr[] 		= sprintf('`k_kjcx`.`process_id` = %d',$v);
                                    $tmp_arr[] 		= sprintf('`k_kjcx`.`%s` = "%s"',$key,$user_bh);
                                    $where_arr[] 	= sprintf('( %s)',implode(' AND ',$tmp_arr));
                                    break;
                            }
                        }

                    }
                }
            }
        }
        return $where_arr;
    }
    //获取机构下的流程
    private function get_process(){
        $process_list=M('CxProcess')->where()->getField('process_id,title,show_user_id,check_user,show_button_tag,check_user_tag,task_menu');
        return $process_list;
    }

    public function down_file(){
        $file_id=$_GET['file_id'];
        if(empty($file_id)){
            redirect("文件不存在跳转页面");
        }else{//如果要加登录条件，这里可以自己加
            $map['id'] = $file_id;
            $list=D('Attachment')->where($map)->select();
            if ($list == false) {//文件不存在，可以跳转到其它页面
                header('HTTP/1.0 404 Not Found');
                header('Location: .');
            } else {
                $file_name="./".$list[0]['dir'].$list[0]['title_r'];//需要下载的文件
                $file_name=iconv("utf-8","gb2312","$file_name");
                if(file_exists($file_name)){
                    $fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
                    if(!file_exists($file_name)){//判断文件是否存在
                        $this->error('文件不存在！');
                    }
                    $file_size=filesize($file_name);//判断文件大小
                    //返回的文件
                    Header("Content-type: application/octet-stream");
                    //按照字节格式返回
                    Header("Accept-Ranges: bytes");
                    //返回文件大小
                    Header("Accept-Length: ".$file_size);
                    //弹出客户端对话框，对应的文件名
                    Header("Content-Disposition: attachment; filename=".$list[0]['title']);
                    //防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
                    $buffer=1024;
                    while(!feof($fp)){
                        $file_data=fread($fp,$buffer);
                        echo $file_data;
                    }
                    //关闭文件
                    fclose($fp);
                }else{
                    $this->error('文件不存在！');
                }

            }
        }
    }
    //获取机构下可执行功能
    private function get_menu_conf(){
        $fun_id=M('MenuConf')->where()->getField('id,title,check_user,check_user_tag,js_fun,tj_ts,control_type,js_fun_param,update_field,ts_message,type,param,process_id,show_button_tag,update_tag');
        return $fun_id;
    }

}